package com.abner.basis.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 分支合并
 *  案例： 1+2+3+4+..100,两个数相加不超过10,超过就拆分
 * @Author yuhui
 * @Date: 2024/3/22
 */
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0,100);

        // 分支合并对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> task = forkJoinPool.submit(myTask);

        System.out.println(task.get());

        forkJoinPool.shutdown();
    }
}

class MyTask extends RecursiveTask<Integer> {

    /**
     * 拆分值
     */
    private static final int val = 10;
    /**
     * 拆分开始值
     */
    private int beginVal;

    /**
     * 拆分结束值
     */
    private int endVal;

    /**
     * 结果
     */
    private int res;

    public MyTask(int beginVal,int endVal) {
        this.beginVal = beginVal;
        this.endVal = endVal;
    }

    /**
     * 拆分+合并
     * @return
     */
    @Override
    protected Integer compute() {
        if((endVal - beginVal) <= val) {
            for (int i = beginVal; i <= endVal; i++) {
                res = res + i;
            }
        }else {
            // 进一步拆分
            int temp = (endVal + beginVal) / 2;
            MyTask leftTask = new MyTask(beginVal, temp);
            MyTask rightTask = new MyTask(temp+1, endVal);

            // 拆分
            leftTask.fork();
            rightTask.fork();

            // 合并
            res = leftTask.join() + rightTask.join();
        }
        return res;
    }
}
